﻿namespace Rio.Manager.Application.ViewModel.FolderTypeAdministration
{
    using System;
    using System.Collections.ObjectModel;
    using System.ServiceModel.DomainServices.Client;
    using System.Windows.Controls;

    using GalaSoft.MvvmLight.Command;
    using GalaSoft.MvvmLight.Messaging;

    using NetBay.Core.BusinessEntities;
    using NetBay.Core.BusinessEntities.Workflow;

    using Rio.Applications.Web.Services;
    using Rio.Framework.Localisation;
    using Rio.Framework.Pages;
    using Rio.Framework.Pages.Context;
    using Rio.Manager.Application.ViewModel.BaseClass;
    using Rio.Manager.Application.ViewModel.Locator;

    public class ManageWorkflowModelTabViewModel : TabViewModelBase
    {
        #region Fields

        private string _DeleteWorkflowTextblock;
        private string _NewWorkflowTexBlock;
        private string _RefreshTextblock;
        private WorkflowModel _selectedWorkflow;
        private string _WorkflowDefinitionsGridView_Description;
        private string _WorkflowDefinitionsGridView_Name;
        private ObservableCollection<WorkflowModel> _workflowModels;
        private string _WorkflowModelsTextblock;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ManageWorkflowTabViewModel"/> class.
        /// </summary>
        public ManageWorkflowModelTabViewModel()
            : base()
        {
            CanCloseTab = true;
            TabIcon = new Uri("/Rio.Manager.Application;component/Assets/Images/manageworkflow.png", UriKind.Relative);
        }

        #endregion Constructors

        #region Properties

        public RelayCommand CreateNewWorkflowCommand
        {
            get;
            set;
        }

        public RelayCommand DeleteWorkflowCommand
        {
            get;
            set;
        }

        public string DeleteWorkflowTextblock
        {
            get { return _DeleteWorkflowTextblock; }
            set
            {
                _DeleteWorkflowTextblock = value;
                RaisePropertyChanged("DeleteWorkflowTextblock");
            }
        }

        public RelayCommand InitializationCommand
        {
            get;
            set;
        }

        public string NewWorkflowTexBlock
        {
            get { return _NewWorkflowTexBlock; }
            set
            {
                _NewWorkflowTexBlock = value;
                RaisePropertyChanged("NewWorkflowTexBlock");
            }
        }

        public RelayCommand RefreshCommand
        {
            get;
            set;
        }

        public string RefreshTextblock
        {
            get { return _RefreshTextblock; }
            set
            {
                _RefreshTextblock = value;
                RaisePropertyChanged("RefreshTextblock");
            }
        }

        public override FolderType SelectedFolderType
        {
            get
            {
                return base.SelectedFolderType;
            }
            set
            {
                base.SelectedFolderType = value;
                RaisePropertyChanged("SelectedFolderType");

                LoadOrRefreshWorkflowList();
            }
        }

        public WorkflowModel SelectedWorkflow
        {
            get { return _selectedWorkflow; }
            set
            {
                _selectedWorkflow = value;

                RaisePropertyChanged("SelectedWorkflow");

                DeleteWorkflowCommand.RaiseCanExecuteChanged();
            }
        }

        public string WorkflowDefinitionsGridView_Description
        {
            get { return _WorkflowDefinitionsGridView_Description; }
            set
            {
                _WorkflowDefinitionsGridView_Description = value;
                RaisePropertyChanged("WorkflowDefinitionsGridView_Description");
            }
        }

        public string WorkflowDefinitionsGridView_Name
        {
            get { return _WorkflowDefinitionsGridView_Name; }
            set
            {
                _WorkflowDefinitionsGridView_Name = value;
                RaisePropertyChanged("WorkflowDefinitionsGridView_Name");
            }
        }

        public ObservableCollection<WorkflowModel> WorkflowModels
        {
            get { return _workflowModels; }
            set
            {
                _workflowModels = value;
                RaisePropertyChanged("WorkflowModels");
            }
        }

        public string WorkflowModelsTextblock
        {
            get { return _WorkflowModelsTextblock; }
            set
            {
                _WorkflowModelsTextblock = value;
                RaisePropertyChanged("WorkflowModelsTextblock");
            }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Creates the new workfow.
        /// </summary>
        public void CreateNewWorkfow()
        {
            TabViewModelBase newTab = ViewModelLocator.NewWorkflowTabViewModelStatic;

            newTab.SelectedOrganization = SelectedOrganization;
            newTab.SelectedFolderType = SelectedFolderType;

            AddTab(newTab);
        }

        /// <summary>
        /// Inits the commands.
        /// </summary>
        public override void InitCommands()
        {
            InitializationCommand = new RelayCommand(Initialization);

            CreateNewWorkflowCommand = new RelayCommand(CreateNewWorkfow);

            RefreshCommand = new RelayCommand(LoadWorkflowModels);

            DeleteWorkflowCommand = new RelayCommand(
                DeleteWorkflow,
                () => SelectedWorkflow != null && !SelectedWorkflow.IsSystem);
        }

        /// <summary>
        /// Inits the labels.
        /// </summary>
        public override void InitLabels()
        {
            TabTitle = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_TABTITLE);
            WorkflowModelsTextblock = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_WORKFLOWMODELSTEXTBLOCK);
            NewWorkflowTexBlock = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_NEWWORKFLOWTEXBLOCK);
            DeleteWorkflowTextblock = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_DELETEWORKFLOWTEXTBLOCK);
            RefreshTextblock = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_REFRESHTEXTBLOCK);
            WorkflowDefinitionsGridView_Name = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_WORKFLOWDEFINITIONSGRIDVIEW_NAME);
            WorkflowDefinitionsGridView_Description = Resx.GetLabel(ResxRioManager.MANAGEWORKFLOWMODELTABVIEWMODEL_WORKFLOWDEFINITIONSGRIDVIEW_DESCRIPTION);
        }

        /// <summary>
        /// Refreshes the workflow list.
        /// </summary>
        public void LoadOrRefreshWorkflowList(NotificationMessage msg = null)
        {
            LoadWorkflowModels();
        }

        /// <summary>
        /// Deletes the workflow.
        /// </summary>
        private void DeleteWorkflow()
        {
            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            businessEntitiesDomainContext.DeleteModel(
                SelectedWorkflow.Identifier,
                (result) =>
                {
                    SelectedWorkflow = null;

                    if (result.HasError || !result.Value.Value)
                    {
                        ShowModalDialog(
                            Resx.GetLabel(ResxCommon.ERROR),
                            Resx.GetLabel(ResxRioManager.WORKFLOWMODEL_DELETE_ERROR), 
                            MessageBoxButtons.Ok, 
                            MessageBoxIcon.Warning);
                    }
                    else
                    {
                        ShowModalDialog(
                            String.Empty, 
                            Resx.GetLabel(ResxRioManager.WORKFLOWMODEL_DELETE_SUCCESS), 
                            MessageBoxButtons.Ok, 
                            MessageBoxIcon.Information);

                        LoadOrRefreshWorkflowList();
                    }
                },
                null);
        }

        /// <summary>
        /// Initializations this instance.
        /// </summary>
        private void Initialization()
        {
            InitLabels();

            LoadOrRefreshWorkflowList();

            Messenger.Default.Register<NotificationMessage>(this, LoadOrRefreshWorkflowList);
        }

        /// <summary>
        /// Loads the workflow models.
        /// </summary>
        private void LoadWorkflowModels()
        {
            BusyIndicator.Clear();
            BusyIndicator.AddBusyTask();

            BusinessEntitiesDomainContext businessEntitiesDomainContext = GlobalWebContext.BusinessEntitiesDomainContext;
            var query = businessEntitiesDomainContext.GetWorkflowModelsQuery();

            businessEntitiesDomainContext.Load(
                query,
                delegate(LoadOperation<WorkflowModel> retr)
                {
                    BusyIndicator.RemoveBusyTask();

                    if (!retr.HasError && retr.Entities != null)
                    {
                        WorkflowModels = new ObservableCollection<WorkflowModel>(retr.Entities);
                    }
                },
                null);
        }

        #endregion Methods
    }
}